import logging
import json

from datetime import datetime, timedelta
import requests

from odoo import api, http
from odoo.http import request
from odoo.addons.web.controllers.main import Home as Home
from odoo.exceptions import ValidationError
from ..tools import sign_tools

_logger = logging.getLogger(__name__)


class Main(Home):

    @http.route(['/ro/api/gjp/get_token/v1'], type='http', auth="none", website=True)
    def gjp_get_token_v1(self, **kw):
        auth_code = kw['auth_code']

        app_key = request.env['ir.config_parameter'].sudo().get_param('ro_base_api.app_id')
        app_secret = request.env['ir.config_parameter'].sudo().get_param('ro_base_api.app_secret')
        app_sign_key = request.env['ir.config_parameter'].sudo().get_param('ro_base_api.app_sign_key')
        app_env_selection = request.env['ir.config_parameter'].sudo().get_param('ro_base_api.app_env_selection')
        tool = sign_tools.SignTools()

        # 创建 参数p
        json_param = json.dumps({
            'TimeStamp': (datetime.utcnow() + timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S'),
            'GrantType': 'auth_token',
            'AuthParam': auth_code
        }, separators=(',', ':'))
        print(json_param)
        p = tool.aes_encode(json_param, app_secret, app_secret[5:21])
        print(p)

        # 创建 参数sign
        sign_data = json.dumps({
            'appkey': app_key,
            'p': p,
            'signkey': app_sign_key
        }, separators=(',', ':'))
        sign = tool.sha256_encode(sign_data)
        print(sign)

        # 请求链接
        if app_env_selection == 'test':
            post_url = 'http://d7.mygjp.com.cn:8013/api/token'
        elif app_env_selection == 'online':
            post_url = 'http://apigateway.wsgjp.com.cn/api/token'
        # 请求数据
        headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
        post_data = {
            'appkey': app_key,
            'p': p,
            'sign': sign
        }
        try:
            response = requests.post(url=post_url, data=post_data, headers=headers)
        except Exception:
            raise ValidationError('请求失败')
        print(response)
        print(response.text)
        # 取得 返回值
        content = json.loads(response.content.decode('utf-8'))
        if content['iserror']:
            request.env['ro.api.log'].sudo().create({
                'host': response.request.url,
                'status': response.status_code,
                'path': response.request.path_url,
                'method': response.request.method,
                'type': 'in',
                'message': response.content.decode('utf-8'),
                'body': response.request.body,
                'api_method': '获取授权',
            })
            raise ValidationError(str(content['errorcode']) + ' ' + content['errormessage'])
        else:
            value = json.loads(tool.aes_decode(content['response']['response'], app_secret, app_secret[5:21]))
        print(value)
        # 将token 及 refresh token 存入系统
        request.env['ir.config_parameter'].sudo().set_param('ro_base_api.app_access_token', value['auth_token'])
        request.env['ir.config_parameter'].sudo().set_param('ro_base_api.app_refresh_token', value['refresh_token'])
        # 将过期时间存入系统
        request.env['ir.config_parameter'].sudo().set_param('ro_base_api.app_expires_in',
                                                            str(datetime.now() + timedelta(hours=8) + timedelta(
                                                                seconds=value['expires_in']))[:19])
        request.env['ir.config_parameter'].sudo().set_param('ro_base_api.app_re_expires_in',
                                                            str(datetime.now() + timedelta(hours=8) + timedelta(
                                                                seconds=value['re_expires_in']))[:19])

        # 记录日志
        request.env['ro.api.log'].sudo().create({
            'host': response.request.url,
            'status': response.status_code,
            'path': response.request.path_url,
            'method': response.request.method,
            'type': 'in',
            'message': response.content.decode('utf-8'),
            'body': response.request.body,
            'api_method': '获取授权',
        })

        return '授权成功'
